//
//  AnniversaryTableViewController.swift
//  BirthdayManager
//
//  Created by Apple on 2020/12/16.
//  Copyright © 2020 Charles. All rights reserved.
//

import UIKit

class AnniversaryTableViewController: UITableViewController {

    var daylist: [dayinfo] = [dayinfo]()
    
    @IBAction func saveToList(segue: UIStoryboardSegue) {
        if let sourceVC = segue.source as? AnniversaryViewController, let day = sourceVC.dayForEdit{
            if let selectedIndex = tableView.indexPathForSelectedRow{
                daylist[selectedIndex.row] = day
                tableView.reloadRows(at: [selectedIndex], with: UITableView.RowAnimation.automatic)
            }else {
                daylist.append(day)
                tableView.reloadData()
            }
        }
        saveAnniversary()
    }
    
    func saveAnniversary() {
        let success = NSKeyedArchiver.archiveRootObject(daylist, toFile: dayinfo.userPath)
        if !success {
            print("failed...")
        }
    }
    func loadAnniversary() {
        if let days = NSKeyedUnarchiver.unarchiveObject(withFile: dayinfo.userPath) as? [dayinfo] {
            daylist = days
            print("load file successful")
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = 330
        loadAnniversary()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return daylist.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "daycell", for: indexPath) as! AnniversaryTableViewCell
        
        
        // Configure the cell...
        cell.headimg?.image = daylist[indexPath.row].headimg
        cell.dayname?.text = daylist[indexPath.row].dayname
        cell.date?.text = daylist[indexPath.row].date?.toString(dateFormat: "yyyy/MM/dd")
        
        let count = daycount(anniversary: daylist[indexPath.row].date!)
        let year = yearcount(anniversary: daylist[indexPath.row].date!)
        
        if (count=="365"||count=="366") {
            cell.status?.text="\(year)周年快乐！"
        } else {
            cell.status?.text = "距离\(year)周年还有\(count)天"
        }
        
        return cell
        
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            daylist.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            saveAnniversary()
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if let destVC = segue.destination as? AnniversaryViewController{
            if let selectedIndex = tableView.indexPathForSelectedRow?.row{
                destVC.dayForEdit = daylist[selectedIndex]
            }
        }
        
    }
    
}
